import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, Platform, PermissionsAndroid, TextInput, Modal, Alert, NativeEventEmitter, NativeModules,DeviceEventEmitter } from 'react-native';
import { Container, Content, View, Button, Text, Item, Icon, Toast } from 'native-base';
import { ListItem } from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import CameraRoll from "@react-native-community/cameraroll";
import ImagePicker from 'react-native-image-crop-picker';
import { Geolocation } from 'react-native-baidu-map';
// import LocalBarcodeRecognizer from 'react-native-local-barcode-recognizer';
import { connect } from 'react-redux';
// import { openSettings } from 'react-native-permissions';

import { Header, Loading, SmsCodeButton } from '../../component';
import { Colors, Metrics } from '../../theme';
import Http from '../../utils/HttpPost';
import ParamsValidate from '../../utils/ValueValidate';


class Register extends Component {
	constructor(props) {
		super(props);
		this._SendVcode = this._SendVcode.bind(this)
		this.state = {
			phone: '',
			smsCode: '',
			password: '',
			passwordAgain: '',
			isLoading: false,
			modalVisible: false,
			photos: [],
			inviteCode: '',
			countryPickerVisible: false,
			countryCode: "86",
			contryCodeLabel: `中国大陆 +86`
		}
	}


	UNSAFE_componentWillMount() {

	}

	componentDidMount() {
		this.eventEmitter = DeviceEventEmitter.addListener('rigisterScan', (event) => {
			if (this.props.scanningType == 'register') {
				this.setState({ inviteCode: event.scanningVal, modalVisible: true })
			}
		})
	
	}

	componentWillUnmount() {
		this.eventEmitter.remove(); // Removes the listener
	}


	// 路由地址
	toNavigateFunc(uri) {
		this.setModalVisible(false)
		this.props.navigation.navigate(uri)
	}
	// 展示model
	setModalVisible(visible) {
		this.setState({ modalVisible: visible });
	}

	/* 发送验证码 */
	_SendVcode(shouldStartCountting) {
		let phone = this.state.phone;
		// 手机号格式校验
		let msg = ParamsValidate('phone', phone);
		if (msg !== null) {
			Toast.show({
				text: msg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			setTimeout(() => { shouldStartCountting && shouldStartCountting(false) }, 0);
			return;
		}

		Http('post', "/user/sendSms", {
			phone,
			purpose: 'register'
		}).then(res => {
			if (res.code === 200) {
				setTimeout(() => { shouldStartCountting && shouldStartCountting(true) }, 0);
				Toast.show({ text: "验证码已发送", position: "top", textStyle: { textAlign: "center" }, type: "success" });
			} else {
				setTimeout(() => { shouldStartCountting && shouldStartCountting(false) }, 0);
			}
		})
	}

	showXiayibu() {
		this.getFirstImgFunc();
		this.setModalVisible(true);
	}

	// 前往相机
	toScanningFunc() {
		this.setModalVisible(false)
		this.props.setGlobalInfo({ scanningType: 'register' })
		this.props.navigation.navigate('Scanning')
	}

	// 获取第一张图片
	async getFirstImgFunc() {
		if (Platform.OS === 'android') {
			try {
				await PermissionsAndroid.request(
					PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
					{
						title: '请求权限',
						message:
							'读取设备上的照片及文件',
					},
				);
			} catch (err) {
				console.warn(err);
			}
		}

		CameraRoll.getPhotos({
			first: 1,
			assetType: 'Photos'
		}).then(res => {
			console.log(res.edges[0].node)
			this.setState({ photos: res.edges });
		}).catch((err) => {
			//Error Loading Images
		});
	}

	// 选择图片识别二维码
	getImgListFunc() {
		ImagePicker.openPicker({
			cropperToolbarTitle: '选取图片',
			mediaType: 'photo',
			includeBase64: true
		}).then((res) => {
			Toast.show({ text: "图片不存在二维码或图片不清晰", position: "top", textStyle: { textAlign: "center" }, type: "warning" });
			// LocalBarcodeRecognizer.decode(res.data.replace("data:image/jpeg;base64,", ""), { codeTypes: ['ean13', 'qr'] }).then((result) => {
			// 	console.log('识别结果：' + result);
			// 	if (result) {
			// 		this.setState({ inviteCode: result });
			// 	} else {
			// 		Toast.show({ text: "图片不存在二维码或图片不清晰", position: "top", textStyle: { textAlign: "center" }, type: "warning" });
			// 	}
			// });
		}).catch(err => {
			console.log('用户取消');
		})
	}

	// 注册
	async registerFunc() {
		let { phone, smsCode, password, passwordAgain, inviteCode } = this.state;

		let phoneMsg = ParamsValidate('phone', phone);
		if (phoneMsg !== null) {
			Toast.show({
				text: phoneMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return;
		}

		let smsCodeMsg = ParamsValidate('smsCode', smsCode);
		if (smsCodeMsg !== null) {
			Toast.show({
				text: smsCodeMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		let passwordMsg = ParamsValidate('password', password);
		if (passwordMsg !== null) {
			Toast.show({
				text: passwordMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		if (password != passwordAgain) {
			Toast.show({
				text: '两次密码输入不一致',
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		let inviteCodeMsg = ParamsValidate('isEmpty', inviteCode);
		if (inviteCodeMsg !== null) {
			Toast.show({
				text: inviteCodeMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		let positionX = 0;
		let positionY = 0;
		try {
			let locationObj = await Geolocation.getCurrentPosition();
			if (locationObj) {
				positionX = locationObj.latitude;
				positionY = locationObj.longitude;
			}
		} catch (e) {
			console.error(e)
		}
		// if (!positionX||!positionY){
		// 	Alert.alert('提示', 'APP未获取位置信息,请前往设置！', [
		// 		{
		// 			text: '去设置',
		// 			onPress: () => {
		// 				 openSettings()

		// 			}
		// 		}
		// 	]);
		// 	return false;
		// }

		this.setState({ isLoading: true })
		Http('post', "/user/regist", {
			countryCode: '86',
			nickName: '火柴',
			phone,
			smsCode,
			password,
			positionX,
			positionY,
			inviter: inviteCode
		}).then(res => {
			this.setState({ isLoading: false, modalVisible: false })
			if (res.code === 200) {
				Toast.show({ text: "注册成功！", textStyle: { textAlign: "center" }, type: "success" });
				this.props.navigation.navigate('Login');
			}
		})
	}

	render() {
		return (
			<Container>
				<Header title="注册" onLeftPress={() => this.props.navigation.goBack()} />
				<Loading showLoading={this.state.isLoading} />
				<Content padder>

					<TextInput
						style={Styles.inputText}
						placeholder='请输入手机号'
						keyboardType='phone-pad'
						// errorMessage='请输入正确的手机号码'
						value={this.state.phone}
						onChangeText={(value) => this.setState({ phone: value })}
					/>

					<View style={Styles.formItem}>
						<TextInput
							style={[Styles.inputText,{flex: 1}]}
							placeholder="请输入验证码"
							keyboardType='numeric'
							value={this.state.smsCode}
							onChangeText={(value) => this.setState({ smsCode: value })}
						/>
						<SmsCodeButton
							textStyle={{ color: 'white', fontSize: 12 }}
							style={{}}
							buttonStyle={{}}
							timerCount={60}
							timerTitle={'获取验证码'}
							enable={this.state.phone.length == 11}
							onClick={
								(shouldStartCountting) => {
									this._SendVcode(shouldStartCountting)
								}}
							timerEnd={() => { this.setState({ state: '倒计时结束' }) }}
						/>
					</View>


					<TextInput
						style={Styles.inputText}
						placeholder="请输入密码"
						// errorMessage='密码最少为数字+字母，8-16位组成'
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ password: value })}
					/>

					<TextInput
						style={Styles.inputText}
						placeholder="请再次确认密码"
						// errorMessage='两次密码不一致'
						keyboardType="visible-password"
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ passwordAgain: value })}
					/>

					<View style={Styles.signInView}>
						<TouchableOpacity onPress={() => {
							this.setModalVisible(true);
						}}
						>
							<LinearGradient style={[Styles.signInBtn]} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
								<Text style={{ fontSize: 14, padding: 12, color: Colors.bai }}>下一步</Text>
							</LinearGradient>
						</TouchableOpacity>
					</View>

					<Text style={Styles.yhXieyi}>
						登录/注册代表您已同意
						<Text onPress={() => this.props.navigation.navigate("ServiceAgreement")} style={Styles.yhXieyiText}> 用户协议 </Text>
						与
						<Text onPress={() => this.props.navigation.navigate("PrivacyPolicy")} style={Styles.yhXieyiText}> 用户隐私协议 </Text>
					</Text>


					<Modal
						style={{ position: 'relative' }}
						animationType="slide"
						transparent={true}
						visible={this.state.modalVisible}
						onRequestClose={() => {
							this.setModalVisible(!this.state.modalVisible)
						}}
					>
						<TouchableOpacity onPress={() => { this.setModalVisible(!this.state.modalVisible) }} style={{ flex: 1 }} ></TouchableOpacity>
						<View style={{ position: 'absolute', bottom: 0, width: Metrics.screenWidth, backgroundColor: '#303438' }}>
							<TouchableOpacity style={{ position: 'absolute', top: 10, right: 10, zIndex: 1, width: 28, height: 28, justifyContent: 'center', alignItems: 'center', backgroundColor: '#576062', borderRadius: 20 }} onPress={() => { this.setModalVisible(!this.state.modalVisible) }}>
								<Icon type="AntDesign" name="close" style={{ color: 'white', fontSize: 18 }} />
							</TouchableOpacity>
							<View style={Styles.yaoqingCont}>

								<Text style={Styles.yaoqiTitText}>您的邀请码为：</Text>

								<View style={Styles.signInView}>
									<TextInput
										value={this.state.inviteCode}
										onChangeText={(value) => this.setState({ inviteCode: value })}
										style={Styles.inputTextYaoqing}
										placeholder="请输入邀请码"
										placeholderTextColor='#7E8285'
									/>

									<TouchableOpacity
										onPress={() => { this.registerFunc() }}
										disabled={this.state.isLoading}>
										<LinearGradient style={[Styles.signInBtn]} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
											<Text style={{ fontSize: 14, padding: 12, color: Colors.bai }}>{`${this.state.isLoading ? "注册中..." : "注册"}`}</Text>
										</LinearGradient>
									</TouchableOpacity>
								</View>

								<Text style={Styles.yaoqiDescText}>或选择其中一种方式填入邀请码</Text>
								<View style={Styles.saomaCont}>
									<View style={Styles.saomaItemCont}>
										<TouchableOpacity style={Styles.saomaIconCont} onPress={() => this.toScanningFunc()}>
											<Icon type="AntDesign" name="qrcode" style={{ color: Colors.subjectJbZuo, fontSize: 20 }} />
										</TouchableOpacity>
										<Text style={Styles.saomaItemText}>摄像机扫描</Text>
									</View>

									<View style={Styles.saomaItemCont}>
										<TouchableOpacity style={Styles.saomaIconCont} onPress={() => this.getImgListFunc()}>
											<Icon type="FontAwesome" name="photo" style={{ color: Colors.subjectJbZuo, fontSize: 20 }} />
										</TouchableOpacity>
										<Text style={Styles.saomaItemText}>从相册选择</Text>
									</View>
								</View>


							</View>

						</View>
					</Modal>

				</Content>
			</Container>
		);
	}

}

const mapStateToProps = state => ({
	logged: state.user.logged,
	token: state.user.token,
	scanningType: state.global.scanningType
});

const mapDispatchToProps = dispatch => ({
	setGlobalInfo: globalInfo => dispatch({ type: 'SET_GLOBALINFO', payload: { globalInfo } }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Register);

const Styles = StyleSheet.create({
	signInView: { marginTop: 18, alignItems: "center" },
	signInBtn: { width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 },
	resetPwd: { width: Metrics.screenWidth * 0.5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 2 },
	inputText: { fontSize: Metrics.fontSize14, marginTop: 6, padding: 6 },
	inputTextYaoqing: { fontSize: 14, marginTop: 8, marginBottom: 28, width: Metrics.screenWidth * 0.6, borderRadius: 8, backgroundColor: '#5A5F62', color: Colors.bai, padding: 6 },
	yhXieyi: { fontSize: 12, color: Colors.hui99, textAlign: 'center', marginTop: 88 },
	yhXieyiText: { fontSize: 12, color: Colors.hui33, },
	formItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', },
	yaoqingCont: { marginTop: 22, paddingBottom: 20 },
	yaoqiTitText: { textAlign: "center", fontSize: 14, color: '#73777A' },
	yaoqiDescText: { textAlign: "center", fontSize: 12, marginTop: 18, color: '#73777A' },
	saomaCont: { flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', marginTop: 20 },
	saomaItemCont: { justifyContent: 'center', alignItems: 'center' },
	saomaIconCont: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 50, height: 50, backgroundColor: '#576062', borderRadius: 25 },
	saomaItemText: { textAlign: "center", fontSize: 16, marginTop: 8, color: 'white' },
})